import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Switch,
  Popconfirm,
  Message,
  Typography,
} from '@arco-design/web-react'
import { IconPlus, IconSearch, IconEdit, IconDelete, IconSettings } from '@arco-design/web-react/icon'
import {
  getWorkflows,
  deleteWorkflow,
  enableWorkflow,
  disableWorkflow,
} from '@/api/workflow'
import type { WorkflowDefinition } from '@/types'
import WorkflowFormModal from '@/components/WorkflowFormModal'
import GitTriggerModal from '@/components/GitTriggerModal'
import dayjs from 'dayjs'
import './index.css'

const { Title } = Typography

export default function Workflow() {
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)
  const [workflows, setWorkflows] = useState<WorkflowDefinition[]>([])
  const [searchText, setSearchText] = useState('')
  const [formVisible, setFormVisible] = useState(false)
  const [editingWorkflow, setEditingWorkflow] = useState<WorkflowDefinition | null>(null)
  const [triggerModalVisible, setTriggerModalVisible] = useState(false)
  const [selectedWorkflow, setSelectedWorkflow] = useState<WorkflowDefinition | null>(null)

  // 加载工作流列表
  const loadWorkflows = async () => {
    setLoading(true)
    try {
      const data = await getWorkflows()
      setWorkflows(data)
    } catch (error) {
      console.error('Failed to load workflows:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadWorkflows()
  }, [])

  // 切换启用/禁用
  const handleToggleEnabled = async (id: number, isEnabled: boolean) => {
    try {
      if (isEnabled) {
        await disableWorkflow(id)
        Message.success('已禁用工作流')
      } else {
        await enableWorkflow(id)
        Message.success('已启用工作流')
      }
      loadWorkflows()
    } catch (error) {
      console.error('Failed to toggle workflow:', error)
    }
  }

  // 删除工作流
  const handleDelete = async (id: number) => {
    try {
      await deleteWorkflow(id)
      Message.success('删除成功')
      loadWorkflows()
    } catch (error) {
      console.error('Failed to delete workflow:', error)
    }
  }

  // 过滤数据
  const filteredData = workflows.filter((item) =>
    item.name.toLowerCase().includes(searchText.toLowerCase())
  )

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => <strong>{name}</strong>,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'isEnabled',
      key: 'isEnabled',
      width: 120,
      render: (isEnabled: boolean, record: WorkflowDefinition) => (
        <Switch
          checked={isEnabled}
          onChange={() => handleToggleEnabled(record.id, isEnabled)}
        />
      ),
    },
    {
      title: '创建人',
      dataIndex: 'createdBy',
      key: 'createdBy',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 320,
      render: (_: any, record: WorkflowDefinition) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<IconEdit />}
            onClick={() => navigate(`/workflow/${record.id}/edit`)}
          >
            编辑
          </Button>
          <Button
            size="small"
            icon={<IconSettings />}
            onClick={() => {
              setSelectedWorkflow(record)
              setTriggerModalVisible(true)
            }}
          >
            触发器
          </Button>
          <Popconfirm
            title="确定要删除此工作流吗？"
            onOk={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" size="small" status="danger" icon={<IconDelete />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div className="workflow-page">
      <Title heading={4} style={{ marginBottom: 20 }}>
        工作流管理
      </Title>

      <Card>
        <div className="workflow-toolbar">
          <Space>
            <Button
              type="primary"
              icon={<IconPlus />}
              onClick={() => {
                setEditingWorkflow(null)
                setFormVisible(true)
              }}
            >
              创建工作流
            </Button>
          </Space>

          <Input
            style={{ width: 300 }}
            placeholder="搜索工作流名称"
            prefix={<IconSearch />}
            value={searchText}
            onChange={setSearchText}
            allowClear
          />
        </div>

        <Table
          columns={columns}
          data={filteredData}
          loading={loading}
          pagination={{
            pageSize: 10,
            showTotal: true,
            showJumper: true,
            sizeCanChange: true,
          }}
          rowKey="id"
          style={{ marginTop: 16 }}
        />
      </Card>

      <WorkflowFormModal
        visible={formVisible}
        workflow={editingWorkflow}
        onCancel={() => {
          setFormVisible(false)
          setEditingWorkflow(null)
        }}
        onSuccess={() => {
          setFormVisible(false)
          setEditingWorkflow(null)
          loadWorkflows()
        }}
      />

      {selectedWorkflow && (
        <GitTriggerModal
          visible={triggerModalVisible}
          workflowId={selectedWorkflow.id}
          workflowName={selectedWorkflow.name}
          onCancel={() => {
            setTriggerModalVisible(false)
            setSelectedWorkflow(null)
          }}
        />
      )}
    </div>
  )
}
